import {
    getItems,
    getItemById,
    createItem,
    createItems,
    updateItem,
    updateItems,
    deleteItem,
    deleteItems,
    directus,                
} from "@/api/directus";

const COLLECTION = "link_insert";

export type DirectusStatus = "published" | "draft" | "archived";

export type LinkInsertItem = {
    id: string | number;
    query?: string;
    title?: string;
    page_url?: string;
    sence?: string;
    position?: string;
    summary?: string;
    status?: DirectusStatus;
    date_created?: string;
    date_updated?: string;
};

export type ListParams = {
    page?: number;
    pageSize?: number;
    keyword?: string;
    sort?: string;
    excludeStatus?: DirectusStatus | "";
};

const BASE_FIELDS = [
    "id",
    "query",
    "title",
    "page_url",
    "sence",
    "position",
    "summary",
    "status",
    "date_created",
];

/** 列表 */
export async function getLinkInsertList(params: ListParams = {}) {
    const { page = 1, pageSize = 10, keyword = "", sort = "id", excludeStatus = "archived" } = params;

    const filter: any = {};
    if (excludeStatus) filter.status = { _neq: excludeStatus };
    if (keyword?.trim()) {
        filter._or = [
            { query: { _contains: keyword } },
            { title: { _contains: keyword } },
            { page_url: { _contains: keyword } },
            { summary: { _contains: keyword } },
        ];
    }

    const { data, meta } = await getItems<LinkInsertItem>(COLLECTION, {
        fields: BASE_FIELDS,
        page,
        limit: pageSize,
        sort,
        filter,
        meta: "filter_count",
    });

    const total = Number(meta?.filter_count ?? 0);
    return { list: data, total };
}

/** 详情 */
export function getLinkInsertById(id: string | number, fields: string[] = BASE_FIELDS) {
    return getItemById<LinkInsertItem>(COLLECTION, id, fields);
}

/** 新增（单条） */
export function createLinkInsert(payload: Partial<LinkInsertItem>) {
    const { query, title, page_url, sence, position, summary, status } = payload;
    return createItem<LinkInsertItem>(COLLECTION, { query, title, page_url, sence, position, summary, status });
}

/** 更新（单条） */
export function updateLinkInsert(id: string | number, payload: Partial<LinkInsertItem>) {
    const { query, title, page_url, sence, position, summary, status } = payload;
    return updateItem<LinkInsertItem>(COLLECTION, id, { query, title, page_url, sence, position, summary, status });
}

/** 批量新增 */
export function createLinkInserts(payloads: Partial<LinkInsertItem>[]) {
    return createItems<LinkInsertItem>(COLLECTION, payloads);
}

type UpdatePayload = Partial<LinkInsertItem> & { id: string | number };

/** 批量更新 */
export function updateLinkInserts(payloads: UpdatePayload[]) {
    return updateItems<LinkInsertItem>(COLLECTION, payloads);
}

/** 删除（单条/批量） */
export function deleteLinkInsert(id: string | number) {
    return deleteItem(COLLECTION, id);
}
export function deleteLinkInserts(ids: (string | number)[]) {
    return deleteItems(COLLECTION, ids);
}

/** 启用/停用 */
export function enableLinkInsert(id: string | number) {
    return updateItem<LinkInsertItem>(COLLECTION, id, { status: "published" });
}
export function disableLinkInsert(id: string | number) {
    return updateItem<LinkInsertItem>(COLLECTION, id, { status: "draft" });
}

/** 导出 */
export async function exportLinkInsertsJSON(opts?: {
    ids?: (string | number)[];
    keyword?: string;
    excludeStatus?: DirectusStatus | "";
    limit?: number;
}) {
    const { ids, keyword = "", excludeStatus = "archived", limit = 10000 } = opts || {};
    const filter: any = {};
    if (excludeStatus) filter.status = { _neq: excludeStatus };
    if (keyword?.trim()) {
        filter._or = [
            { query: { _contains: keyword } },
            { title: { _contains: keyword } },
            { page_url: { _contains: keyword } },
            { summary: { _contains: keyword } },
        ];
    }
    if (ids?.length) filter.id = { _in: ids.map(String) };

    const { data } = await getItems<LinkInsertItem>(COLLECTION, {
        fields: BASE_FIELDS,
        limit,
        sort: "id",
        filter,
    });

    return new Blob([JSON.stringify(data ?? [], null, 2)], {
        type: "application/json;charset=utf-8",
    });
}

/** 频道下拉 */
export type VerticalCategory = { id: string | number; value: string; query: string };
export async function getVerticalCategories() {
    const { data } = await getItems<VerticalCategory>("vertical_category", {
        fields: ["id", "value", "query"],
        sort: "id",
        page: 1,
        limit: 1000,
    });
    return data || [];
}

/* ===================== 详情 ===================== */
export type LinkInsertDetail = LinkInsertItem & { sence_label?: string };

export async function getLinkInsertDetail(id: string | number): Promise<LinkInsertDetail> {
    const base = await getItemById<LinkInsertItem>(COLLECTION, id, [
        ...BASE_FIELDS,
        "date_updated",
        "cover_image",
    ]);

    const cats = await getVerticalCategories();
    const dict: Record<string, string> = {};
    (cats || []).forEach((it) => {
        const key = it?.value != null ? String(it.value).trim() : "";
        const label = it?.query ?? "";
        if (key) dict[key] = label || key;
    });

    const code = base?.sence ? String(base.sence).trim() : "";
    const sence_label = code ? (dict[code] || code) : "";

    return { ...(base as any), sence_label };
}

/* ===================== 是否选中导出 ===================== */
export async function exportLinkInsertsSelectedOrAll(opts?: {
    selectedIds?: (string | number)[];
    keyword?: string;
    excludeStatus?: DirectusStatus | "";
    limit?: number;
}) {
    const { selectedIds, keyword = "", excludeStatus = "archived", limit } = opts || {};
    const ids = selectedIds && selectedIds.length ? selectedIds : undefined;
    return exportLinkInsertsJSON({ ids, keyword, excludeStatus, limit });
}

/* ===================== 导入 ===================== */
export interface LinkInsertImportResult {
    total?: number;
    inserted?: number;
    created?: number;
    updated?: number;
    skipped?: number;
    failed?: number;
    details?: any;
}

export interface LinkInsertImportExtra {
    format?: "csv" | "json";
    overwrite?: boolean;
    signal?: AbortSignal;
    filename?: string;
}

/** 通过文件导入 */
export async function importLinkInserts(
    file: File | Blob,
    extra?: LinkInsertImportExtra
): Promise<LinkInsertImportResult> {
    const fd = new FormData();
    const name = extra?.filename || (file instanceof File ? file.name : "link_insert.csv");
    fd.append("file", file, name);
    if (extra?.format) fd.append("format", extra.format);
    if (typeof extra?.overwrite === "boolean") {
        fd.append("overwrite", String(extra.overwrite));
    }


    const res: any = await directus.post(`/utils/import/${COLLECTION}`, fd, {
        signal: extra?.signal as any,
    });
    return (res?.data?.data ?? res?.data ?? {}) as LinkInsertImportResult;
}
